package com.prawn.authority.service;

import com.prawn.authority.dao.UserDao;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EmailService {
	@Autowired
	private JavaMailSender mailSender;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	private UserDao userDao;

	//邮件发件人
	@Value("${mail.fromMail.addr}")
	private String from;

	public void sendMail(String toEmail, String title, String checkCode) {
		SimpleMailMessage message = new SimpleMailMessage();
		String content = "【对虾云服务】欢迎使用对虾云服务平台，您的验证码为：" + checkCode + "，请在5分钟内完成验证。";
		message.setFrom(from);
		message.setTo(toEmail);
		message.setSubject(title);
		message.setText(content);
		mailSender.send(message);

		redisTemplate.opsForValue().set("email_" + toEmail, checkCode, 5, TimeUnit.MINUTES);

		//将验证码以及邮箱发送到rabbitMQ中
//		Map<String, String> map = new HashMap<>();
//		map.put("email", toEmail);
//		map.put("checkcode", checkCode);
//		rabbitTemplate.convertAndSend("email", map);
	}


	public boolean checkCode(String fromEmail, String code) {
		if (StringUtils.isEmpty(code)) {
			return false;
		}
		String codeInRedis = (String) redisTemplate.opsForValue().get("email_" + fromEmail);
		return code.equals(codeInRedis);
	}


	public void deleteCode(String fromEmail) {
		redisTemplate.delete("email_" + fromEmail);
	}


	/**
	 * 检查邮箱是否已经注册过
	 *
	 * @param addr
	 * @return false 已被注册，true 未注册
	 */
	public boolean checkEmailRegisted(String addr) {
		return userDao.findByEmail(addr) == null;
	}
}
